function s = slydetrend(s)
% slydetrend  - slyly detrends signal

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

ss = size(s);
if numel(s) == length(s)
    rs = [1,1];
    s = s(:);
    sn = numel(s);
else
    rs = [1, prod(ss(2:end))];
    s = reshape(s, [ss(1), rs(2)]);
    sn = ss(1);
end
sd = sn - 1;
fs = reshape(s(1,:), rs);
ls = reshape(s(end,:), rs);

ps = [fs;fs;s;ls;ls];
ps = convn(ps, [1;1;1]./3, 'same');
ps = diff(ps(2:end-2,:));
mdp = mean(ps);
sdp = std(ps);
gdi = abs((ps-ones(sn, 1)*mdp))<2*(ones(sn, 1)*sdp);
ps(~gdi) = 0;
mdp = sum(ps) ./ sum(gdi);
s = s - ([0:sd]' * mdp) + ((sd/2).*(ones(sn,1)*mdp));
reshape(s, ss);
